package com.springboot.autoconfigure.oss.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.transfer.TransferManager;
import com.amazonaws.services.s3.transfer.TransferManagerBuilder;
import com.amazonaws.services.s3.transfer.Upload;
import com.amazonaws.services.s3.transfer.model.UploadResult;
import com.springboot.autoconfigure.oss.config.JdOSSPropertis;
import com.springboot.autoconfigure.oss.config.OssConfigPropertis;
import com.springboot.autoconfigure.oss.model.FileInfo;
import com.springboot.autoconfigure.oss.model.FileOssOperationStatus;
import com.springboot.autoconfigure.oss.model.FileUploadStatus;
import com.springboot.autoconfigure.oss.service.AbstractFileGetFileName;
import com.springboot.autoconfigure.oss.service.AbstractInitClientServer;
import com.springboot.autoconfigure.oss.service.OssApiService;
import org.springframework.context.annotation.Scope;

import javax.annotation.PostConstruct;
import java.io.File;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @TITLE 京东云oss服务
 * @API https://docs.jdcloud.com/cn/object-storage-service/transfermanager
 */
public class JdOssApiServiceImpl extends AbstractFileGetFileName implements OssApiService<JdOSSPropertis>, AbstractInitClientServer<TransferManager> {
    //文件名层级分隔符号
    private static final String SPLIT_PATH="_";

    //URL 上传指定文件名前缀
    private static final String URL_UPLOAD_PREFIX="UPLOAD-BY-URL";



    private JdOSSPropertis jdOSSPropertis;
    private OssConfigPropertis ossConfigPropertis;


    private  TransferManager transferManager;

    private   AmazonS3 s3;

    public JdOssApiServiceImpl(JdOSSPropertis jdOSSPropertis, OssConfigPropertis ossConfigPropertis) {
        this.jdOSSPropertis = jdOSSPropertis;
        this.ossConfigPropertis = ossConfigPropertis;
    }

    @Override
    public TransferManager getinit(){
        final String accessKey = jdOSSPropertis.getAccessKey();
        final String secretKey = jdOSSPropertis.getSecretkey();
        final String endpoint = "https://s3."+jdOSSPropertis.getRegion()+".jdcloud-oss.com";
        ClientConfiguration config = new ClientConfiguration();

        AwsClientBuilder.EndpointConfiguration endpointConfig =
                new AwsClientBuilder.EndpointConfiguration(endpoint, jdOSSPropertis.getRegion());

        AWSCredentials awsCredentials = new BasicAWSCredentials(accessKey,secretKey);
        AWSCredentialsProvider awsCredentialsProvider = new AWSStaticCredentialsProvider(awsCredentials);
        //初始化s3实例
        AmazonS3 s3 = AmazonS3Client.builder()
                .withEndpointConfiguration(endpointConfig)
                .withClientConfiguration(config)
                .withCredentials(awsCredentialsProvider)
                .disableChunkedEncoding()
                .build();
        this.s3=s3;
        //初始化TransferManager实例
        transferManager = TransferManagerBuilder.standard()
                .withS3Client(s3)
                .build();
        return transferManager;
    }

    @PostConstruct
    public void init(){

    }

    /**
     * 生成文件名称
     * @param file
     * @return
     */
    public String getFileName(File file){
        String fileName=null;
        String extFileName=FileUtil.extName(file);
        if(StrUtil.isEmptyIfStr(extFileName)){
            fileName= FileUtil.mainName(file) + SPLIT_PATH + getFileDate() + SPLIT_PATH + UUID.randomUUID();
        }else {
            fileName = FileUtil.mainName(file) + SPLIT_PATH + getFileDate() + SPLIT_PATH + UUID.randomUUID()+"."+extFileName;
        }
        //指定的路径上传
        if (!StrUtil.isEmptyIfStr(ossConfigPropertis.getFolderPathName())){
            fileName=ossConfigPropertis.getFolderPathName()+fileName;
        }
        return  fileName;
    }

    private String getFileDate() {
        return DatePattern.PURE_DATETIME_MS_FORMAT.format(new Date());
    }

    public String getFileName(URL url){
        return URL_UPLOAD_PREFIX+SPLIT_PATH + getFileDate() + SPLIT_PATH + UUID.randomUUID();
    }



    @Override
    public FileUploadStatus uploadFile(URL url) {
        return null;
    }

    @Override
    public FileUploadStatus uploadFile(URL url,String filePrix){
        return null;
    }

    @Override
    public FileUploadStatus uploadFile(File file) {
        TransferManager transferManager = getinit();
        String uuidFileNameByTypeFile = getUUIDFileNameByTypeFile(file,this.ossConfigPropertis,"");
        String fileKey = uuidFileNameByTypeFile.replaceAll("/", "");
        Upload upload = transferManager.upload(jdOSSPropertis.getBucketName(), fileKey, file);
        try {
            UploadResult uploadResult = upload.waitForUploadResult();
            String key = uploadResult.getKey();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return FileUploadStatus.builder().success(true).fileKey(fileKey).url(jdOSSPropertis.getDomain()+upload).build();
    }

   

    @Override
    public List<FileInfo> getBucketSpaceFile(String prefix, int limit) {
        return null;
    }

    @Override
    public FileUploadStatus uploadAbsoulteFilePath(File file, String filePath) {
        return null;
    }

    @Override
    public FileUploadStatus uploadFile(File file, String fileName) {
        return null;
    }

    @Override
    public FileUploadStatus uploadFileAndCallBack(File file, String callbackUrl) {
        return null;
    }

    @Override
    public List<String> findFile(String... fileNames) {
        return null;
    }


    @Override
    public FileUploadStatus findFileByKey(String fileKey) {
//        S3Object object = this.s3.getObject(jdOSSPropertis.getBucketName(), fileKey);
        String domain = jdOSSPropertis.getDomain();
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(domain);
        stringBuffer.append(fileKey);
        return FileUploadStatus.builder().success(true).fileKey(fileKey).url(stringBuffer.toString()).build();
    }

    @Override
    public FileOssOperationStatus delFile(String... fileNames) {
        getinit();
        for (String fileName : fileNames) {
            this.s3.deleteObject(jdOSSPropertis.getBucketName(),fileName);
        }
        return FileOssOperationStatus.suceess();
    }
}
